const log = require('../../util/log')
const config = require('../../util/config')
const chromeMng = require('../chromeMng.20180824')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = chromeMng.client;

async function checkLoginTaobao(obj) {
  obj = obj || {}
  obj.times = (obj.times || 0) + 1
  log('checking login taobao', obj)
  try {
    Page.navigate({
      url: 'https://pub.alimama.com/index.htm'
    })
    return step1(obj)
  } catch (err) {
    log(err)
  }
}

async function step1(obj) {
  obj.times++
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('超时')
    })
  }
  log('checking login taobao step 1', obj)
  try {
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://pub.alimama.com/index.htm') {
      return step2(obj)
    }
    return new Promise(resolve => {
      setTimeout(() => {
        step1(obj).then(result => {
          resolve(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  obj.times++
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('超时')
    })
  }
  log('checking login taobao step 2', obj)
  try {
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("span.logined-name")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt != 0) {
      return new Promise(resolve => {
        chromeMng.qrcode = ''
        resolve(true)
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt != 0) {
      return new Promise(resolve => {
        resolve(false)
      })
    }
    return new Promise(resolve => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = checkLoginTaobao
